import axios from 'axios'
import Cookies from 'js-cookie'

// 创建axios实例
export const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
  withCredentials: true // 确保发送cookie
})

// 请求拦截器 - 主动设置Cookie头
api.interceptors.request.use(
  config => {
    // 获取SESSDATA cookie
    const sessData = Cookies.get('SESSDATA')
    console.log('请求拦截器 - 获取到的SESSDATA:', sessData ? '有值' : '无值')
    
    if (sessData) {
      // 主动设置Cookie头，确保后端能够获取到
      config.headers.Cookie = `SESSDATA=${sessData}`
      console.log('请求拦截器 - 已设置Cookie头:', config.headers.Cookie)
    } else {
      console.log('请求拦截器 - 未找到SESSDATA，跳过Cookie设置')
    }
    
    console.log('请求详情:', {
      url: config.url,
      method: config.method,
      headers: config.headers,
      withCredentials: config.withCredentials
    })
    
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => response,
  error => {
    console.error('API请求错误:', error)
    return Promise.reject(error)
  }
)

// API方法
export const apiMethods = {
  // 申请登录二维码
  applyLoginQR: () => api.get('/apply'),
  
  // 扫码登录
  scanLogin: () => api.get('/login'),
  
  // 获取登录信息
  getLoginInfo: () => api.get('/loginInfo'),
  
  // 获取视频基本信息
  getVideoInfo: (videoUrl) => api.get('/video/info', { params: { videoUrl } }),
  
  // 下载视频（旧接口，保持兼容）
  downloadVideo: (video) => api.post('/video/download', {
    bvid: video.bvid,
    cid: video.cid,
    qn: video.qn || 80,
    fnval: video.fnval || 16
  }),
  
  // 获取视频下载链接（新接口）
  getVideoDownloadUrls: (videos) => {
    console.log('准备发送下载请求:', videos);
    
    // 如果传入的是单个视频对象，转换为数组
    const videoList = videos.videoList || (Array.isArray(videos) ? videos : [videos]);
    console.log('处理后的视频列表:', videoList);
    
    // 确保每个视频对象都有必要的字段
    const validVideoList = videoList.map(video => {
      if (!video.bvid || !video.cid) {
        console.error('视频信息不完整:', video);
        throw new Error('视频信息不完整');
      }
      return {
        bvid: video.bvid,
        cid: video.cid.toString(),
        qn: video.qn || 80,
        fnval: video.fnval || 16
      };
    });
    
    console.log('发送下载请求数据:', validVideoList);
    return api.post('/video/download', {
      videoList: validVideoList
    });
  },
  
  // 图片代理
  getProxyImage: (imageUrl) => `/api/video/image?url=${encodeURIComponent(imageUrl)}`
}

// 获取下载列表
export const getDownloadList = () => {
  return api.get('/video/download/list')
}

// 获取下载目录路径
export const getDownloadFolderPath = () => {
  return api.get('/video/download/folder/path')
}

// 打开下载目录
export const openDownloadFolder = (folderPath) => {
  const params = folderPath ? { path: folderPath } : {}
  return api.get('/video/download/folder', { params })
}

// 重试下载
export const retryDownload = (id) => {
  return api.post(`/video/download/retry/${id}`)
}

// 删除下载任务
export const deleteDownload = (id) => {
  return api.delete(`/video/download/${id}`)
}

// 清理已完成的下载
export const clearCompletedDownloads = () => {
  return api.delete('/video/download/completed')
} 